/*
 * @Author: jiu yin
 * @Date: 2023-04-27 14:23:19
 * @LastEditTime: 2023-08-09 16:38:20
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \AI admin\src\view\adminRole\index.tsx
 * jiu
 */
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import "./index.scss";
import {
   Space,
   Table,
   Tag,
   Tooltip,
   Modal,
   Upload,
   Button,
   Input,
   Switch,
   Form,
   Popover,
   Transfer,
   message,
   Checkbox,
   theme,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import type { TransferDirection, TransferListProps } from "antd/es/transfer";
import { useNavigate } from "react-router-dom";
import { TweenOneGroup } from "rc-tween-one";

import { list_role, create_role, del_role, edit_role } from "@/api/home";
import { getRandomHexColor, getColorArr } from "@/utils";

import { PlusOutlined } from "@ant-design/icons";
import type { InputRef } from "antd";
import Role from "@/comment/role";
import { butPermission } from "@/utils/auth";

function role() {
   let Permission = butPermission("bc");

   const [form] = Form.useForm();
   let navigate = useNavigate();

   let getColorArrLen = getColorArr().length;

   interface DataType {
      keywords: string;
      role_id: number;
      role_name: string;
      role_type: string;
   }

   const [disabled, setDisabled] = useState(false);

   const roleRef = useRef(null);

   //表格

   const [datas, setDatas] = useState<DataType[]>([]);

   const [pagination, setPagination] = useState({
      current: 1,
      total: 0,
         pageSize: 11,
      hideOnSinglePage: true,
      keyword: "",
   });
   const [updataTable, setUpdataTable] = useState(true);
   useEffect(() => {
      list_role({
         page: pagination.current,
         limit: pagination.pageSize,
         keyword: pagination.keyword,
      }).then(res => {
         if (!res.data.data) res.data.data = [];
         res.data.data.forEach(item => {
            item.key = item.role_id;
         });
         setPagination({ ...pagination, total: res.data.total });
         setDatas([...res.data.data]);
      });
   }, [pagination.current, updataTable, pagination.keyword]);

   const handleTableChange = e => {
      setPagination({ ...pagination, current: e.current });
      // console.log(e);
   };

   const columns: ColumnsType<DataType> = [
      {
         title: "角色名称",
         dataIndex: "role_name",
      },
      {
         title: "备注",
         dataIndex: "remark",
      },
      {
         title: "创建时间",
         dataIndex: "created_at",
      },
      // {
      //     title: '角色',
      //     dataIndex: 'keywords',
      //     render: (_, item) => (
      //         <>
      //             <Popover content={(
      //                 <div className='roleTag'>
      //                     <Space size={[0, 8]} wrap>
      //                         {item.keywords.length > 0 && item.keywords.map((item, index) => {
      //                             return <Tag color={getColorArr()[index % getColorArrLen]} key={index}>{item}</Tag>
      //                         })}
      //                     </Space>
      //                 </div>
      //             )} title="角色角色">
      //                 <div className='tableP'>
      //                     {item.keywords.length > 0 && item.keywords.map((item, index) => {
      //                         return <span key={index}> {item} |&nbsp;</span>
      //                     })}
      //                 </div>
      //             </Popover>

      //         </>
      //     ),

      // },
      // {
      //     title: '近义词',
      //     dataIndex: 'keywords',
      //     key: 'keywords',
      //     render: (_, item) => (
      //         <>
      //             <Tooltip title={item.keywords}>
      //                 <p >{item.keywords}</p>
      //             </Tooltip>
      //         </>
      //     ),
      // },
      // {
      //     title: '状态',
      //     key: 'status',
      //     render: (_, item) => (
      //         <>
      //             <Switch defaultChecked checked={item.status} onChange={(checked) => { SwitchOnchange(checked, item) }} />
      //         </>
      //     ),
      // },
      {
         title: "操作",
         key: "action",
         render: (_, item) => (
            <Space size="middle">
               {Permission && (
                  <a   onClick={() => edit(item)}>
                     编辑
                  </a>
               )}
               {Permission && (
                  <a   onClick={() => confirm(item)}>
                     删除
                  </a>
               )}
            </Space>
         ),
      },
   ];

   let searchInit = { keyword: "" };
   const [search, setSearch] = useState(searchInit);

   //弹框
   const [isModalOpen, setIsModalOpen] = useState(false);

   //取消
   const cancel = () => {
      setIsModalOpen(false);
      form.resetFields();
      setDisabled(false);
      setformData(dataFormRoleInfo);
      setTags([]);
      setRoleList([]);
      setRoleListWrite([]);
   };
   const [type, setType] = useState("");
   let dataFormRoleInfo = {
      role_name: "",
      remark: "",
      role_id: 0,
   };
   const [formData, setformData] = useState(dataFormRoleInfo);
   //重置表单
   useEffect(() => {
      form.setFieldsValue(formData);
   }, [formData]);
   //成功走得
   const onFinish = (values: any) => {
      console.log("Success:", values);
      console.log(type);
      let roleArr = roleRef?.current?.getData();
      //   return  console.log(roleArr);

      if (type == "add") {
         create_role({ ...values, ...roleArr }).then(res => {
            message.success("创建角色成功");
            setIsModalOpen(false);
            setformData(dataFormRoleInfo);
            form.resetFields();
            setUpdataTable(!updataTable);
         });
      } else if (type == "edit") {
         edit_role({ ...values, ...roleArr, role_id: formData.role_id }).then(res => {
            message.success("编辑角色成功");
            setIsModalOpen(false);
            setformData(dataFormRoleInfo);
            form.resetFields();
            setUpdataTable(!updataTable);
            location.reload();
         });
      }
   };

   let [roleList, setRoleList] = useState([]); //读
   let [roleListWrite, setRoleListWrite] = useState([]); //写
   const edit = (item: any) => {
      console.log(item);
      setType("edit");
      setRoleList(item.roleList);
      setRoleListWrite(item.roleListWrite);
      setformData(item);
      setIsModalOpen(true);
   };
   const detail = item => {
      setDisabled(true);
      setformData(item);
      setTags(item.keywords);
      setIsModalOpen(true);
   };

   //失败走得
   const onFinishFailed = (errorInfo: any) => {
      console.log("Failed:", errorInfo);
      // setIsModalOpen(false);
   };

   //上传
   const onChangeUpload = e => {
      console.log(e, "上传");
      if (e.file.response?.code == 200) {
         console.log("上传成功");
      }
   };

   //穿梭框
   let [sourcesList, setSourcesList] = useState([
      {
         id: 1,
         role_name: "尼玛",
      },
      {
         id: 2,
         role_name: "阿斯达",
      },
      {
         id: 3,
         role_name: "打算",
      },
      {
         id: 4,
         role_name: "大多",
      },
      {
         id: 5,
         role_name: "阿斯达",
      },
      {
         id: 6,
         role_name: "得撒奥无",
      },
      {
         id: 7,
         role_name: "萨达",
      },
   ]);

   let [targetList, setTargetList] = useState([] as any[]);

   const setTargetListFn = (targetListObj: any) => {
      setTargetList(() => [...targetListObj]);
   };
   useEffect(() => {
      console.log(targetList, "targetList");
   }, [targetList]);

   //删除确认框
   const [modal, contextHolder] = Modal.useModal();

   //删除确认框
   const confirm = item => {
      modal.confirm({
         title: "删除",
         content: "是否将该条规则从列表中删除？",
         okText: "确认",
         cancelText: "取消",
         onOk() {
            del_role({ role_id: item.role_id }).then(res => {
               message.success("删除成功");
               setUpdataTable(!updataTable);
            });
         },
      });
   };

   let statusStr = (
      <p>
         是否将该条信息从<a  > 已开启 </a>状态变更为<a  > 已停用 </a>？
      </p>
   );
   let statusStr1 = (
      <p>
         是否将该条信息从<a  > 已停用 </a>状态变更为<a  > 已开启 </a>？
      </p>
   );
   let statusStr2 = <p></p>;

   //角色编辑

   const { token } = theme.useToken();
   const [tags, setTags] = useState([] as string[]);
   const [inputVisible, setInputVisible] = useState(false);
   const [inputValue, setInputValue] = useState("");
   const inputRef = useRef<InputRef>(null);

   useEffect(() => {
      if (inputVisible) {
         inputRef.current?.focus();
      }
   }, [inputVisible]);

   const handleClose = (removedTag: string) => {
      const newTags = tags.filter(tag => tag !== removedTag);
      console.log(newTags);
      setTags(newTags);
   };

   const showInput = () => {
      setInputVisible(true);
   };

   const handleInputChange = useCallback(
      (e: React.ChangeEvent<HTMLInputElement>) => {
         setInputValue(e.target.value);
      },
      [inputValue]
   );

   const handleInputConfirm = (e: any) => {
      e.stopPropagation();
      e.preventDefault();
      if (inputValue && tags.indexOf(inputValue) === -1) {
         setTags([...tags, inputValue]);
      }
      setInputVisible(true);
      setInputValue("");
   };

   const forMap = (tag: string, index: number) => {
      const tagElem = (
         <Tag
            closable
            key={index}
            onClose={e => {
               e.preventDefault();
               handleClose(tag);
            }}
            color={getColorArr()[index % getColorArrLen]}
            className="tagSynonym">
            {tag}
         </Tag>
      );
      return (
         <span key={tag} style={{ display: "inline-block" }}>
            {tagElem}
         </span>
      );
   };

   const tagChild = useMemo(() => tags.map(forMap), [tags]);

   const tagPlusStyle = {
      background: token.colorBgContainer,
      borderStyle: "dashed",
      marginLeft: "5px",
   };

   const optionsChenckbox = [
      { role: "角色", value: "1" },
      { role: "媒体", value: "2" },
   ];

   return (
      <div className="intention">
         <div className="title">
            {Permission && (
               <Button
                  type="primary"
                  onClick={() => (
                     setIsModalOpen(true),
                     setDisabled(false),
                     setType("add"),
                     setRoleList([]),
                     setRoleListWrite([])
                  )}>
                  + 新建角色
               </Button>
            )}

            {/* <div className='search'>
                    <Input placeholder="模糊搜索关键字" className='input' value={search.keyword} onChange={(e) => setSearch({ ...search, keyword: e.target.value })} />
                    <Button type="primary" className='ml_10' onClick={() => {
                        setPagination({ ...pagination, keyword: search.keyword })
                    }}>查询</Button>
                    <Button className='ml_10' onClick={() => { setSearch(searchInit), setUpdataTable(!updataTable) }}>重置</Button>
                </div> */}
         </div>
         <Table
            columns={columns}
            dataSource={datas}
            pagination={pagination}
            onChange={handleTableChange}
         />

         {isModalOpen && (
            <Modal
               title={type == "add" ? "创建角色" : "编辑角色"}
               open={isModalOpen}
               onCancel={() => {
                  cancel();
               }}
               keyboard
               footer={null}>
               <Form
                  name="basic"
                  labelCol={{ span: 12, offset: 10 }}
                  wrapperCol={{ span: 100 }}
                  style={{ maxWidth: 600, marginTop: "20px" }}
                  initialValues={formData}
                  onFinish={onFinish}
                  onFinishFailed={onFinishFailed}
                  autoComplete="off"
                  form={form}
                  layout="vertical">
                  <div className="flex">
                     <Form.Item
                        label="角色名"
                        style={{ width: "168px" }}
                        rules={[{ required: true, message: "请输入角色名" }]}
                        name="role_name">
                        <Input placeholder="不超过10字" maxLength={10} />
                     </Form.Item>
                     <Form.Item
                        label="备注"
                        style={{ width: "320px", marginLeft: "10px" }}
                        name="remark">
                        <Input placeholder="不超过30字" maxLength={30} />
                     </Form.Item>
                  </div>

                  <Form.Item
                     label="权限选择"
                     style={{ width: "100%", marginLeft: "10px" }}
                     name="roleList">
                     <div className="paddings searchLogBody">
                        <Role
                           ref={roleRef}
                           type={type}
                           roleList={roleList}
                           roleListWrite={roleListWrite}
                        />
                     </div>
                  </Form.Item>

                  <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                     <div style={{ paddingTop: "10px" }}>
                        <Button type="primary" htmlType="submit">
                           确定
                        </Button>
                        <Button
                           htmlType="button"
                           onClick={() => {
                              cancel();
                           }}
                           className="ml_10">
                           取消
                        </Button>
                     </div>
                  </Form.Item>
               </Form>
            </Modal>
         )}

         {/* 删除确认对话框 */}
         {contextHolder}
      </div>
   );
}

export default role;
